package cn.itcast.bos.web.action.base;

import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.service.base.AreaService;
import cn.itcast.bos.utils.PinYin4jUtils;
import cn.itcast.bos.web.action.base.web.utils.BaseAction;
import com.opensymphony.xwork2.ActionContext;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import sun.misc.BASE64Encoder;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Controller
@Scope("prototype")
@ParentPackage("json-default")
@Namespace("/")
public class AreaAction extends BaseAction<Area> {

    @Autowired
    private AreaService areaService;

    private File file;
    private String fileFileName;

    public void setFile(File file) {
        this.file = file;
    }

    public void setFileFileName(String fileFileName) {
        this.fileFileName = fileFileName;
    }

    // private
    @Action(value = "area_upload")
    public String upload() throws IOException {
        /*
		 * if (fileFileName == null || StringUtils.isBlank(fileFileName) ||
		 * (!fileFileName.endsWith(".xsl") ||
		 * (!fileFileName.endsWith(".xslx")))) { throw new
		 * RuntimeException("请不要搞事情"); }
		 */
        List<Area> areas = new ArrayList<Area>();
        Workbook workbook = null;
        if (fileFileName.endsWith(".xsl")) {
            workbook = new HSSFWorkbook(new FileInputStream(file));
        } else if (!fileFileName.endsWith(".xslx")) {
            workbook = new XSSFWorkbook(new FileInputStream(file));
        }

        Sheet sheet = workbook.getSheet("sheet1");
        for (Row row : sheet) {
            if (row.getRowNum() == 0) {
                continue;
            }
            if(row.getCell(0)==null&&StringUtils.isBlank(row.getCell(0).getStringCellValue())){
                continue;
            }
            Area area = new Area();
            area.setId(row.getCell(0).getStringCellValue());
            area.setProvince(row.getCell(1).getStringCellValue());
            area.setCity(row.getCell(2).getStringCellValue());
            area.setDistrict(row.getCell(3).getStringCellValue());
            area.setPostcode(row.getCell(4).getStringCellValue());
            String province = area.getProvince();
            String district = area.getDistrict();
            String city = area.getCity();
            String address = province.substring(0, province.length() - 1)
                + city.substring(0, city.length() - 1)
                + district.substring(0, district.length() - 1);
            StringBuffer str = new StringBuffer();
            String[] headByString = PinYin4jUtils.getHeadByString(address);
            for (String captal : headByString) {
                str.append(captal);
            }
            area.setShortcode(str.toString());
            area.setCitycode(PinYin4jUtils.hanziToPinyin(city, ""));
            areas.add(area);
        }
        areaService.save(areas);
        workbook.close();
        return NONE;
    }

    @Action(value = "area_pageQuery", results = {@Result(name = "success", type = "json")})
    public String pageQuery() {

        Pageable pageable = new PageRequest(page - 1, rows);

        Specification<Area> spec = new Specification<Area>() {

            @Override
            public Predicate toPredicate(Root<Area> root,
                                         CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> list = new ArrayList<Predicate>();
                if (StringUtils.isNotBlank(model.getProvince())) {
                    Predicate p1 = cb.like(root.get("province")
                        .as(String.class), "%" + model.getProvince() + "%");
                    list.add(p1);
                }
                if (StringUtils.isNotBlank(model.getCity())) {
                    Predicate p2 = cb.like(root.get("city").as(String.class),
                        "%" + model.getCity() + "%");
                    list.add(p2);
                }
                if (StringUtils.isNotBlank(model.getDistrict())) {
                    Predicate p3 = cb.like(root.get("district")
                        .as(String.class), "%" + model.getDistrict() + "%");
                    list.add(p3);
                }

                return cb.and(list.toArray(new Predicate[0]));
            }
        };
        Page<Area> pageData = areaService.findAll(spec, pageable);
        PagePushIntoValueStack(pageData);
        return SUCCESS;
    }

    @Action(value = "area_export")
    public String areaExport() {
        List<Area> areas = areaService.findAll();

        HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
        HSSFSheet sheet = hssfWorkbook.createSheet("sheet1");
        HSSFRow headRow = sheet.createRow(0);
        headRow.createCell(0).setCellValue("区域编号");
        headRow.createCell(1).setCellValue("省份");
        headRow.createCell(2).setCellValue("城市");
        headRow.createCell(3).setCellValue("区域");
        headRow.createCell(4).setCellValue("编码");
        for (int i = 0; i < areas.size(); i++) {
            HSSFRow row = sheet.createRow(i + 1);
            Area area = areas.get(i);
            row.createCell(0).setCellValue(area.getId());
            row.createCell(1).setCellValue(area.getProvince());
            row.createCell(2).setCellValue(area.getCity());
            row.createCell(3).setCellValue(area.getDistrict());
            row.createCell(4).setCellValue(area.getPostcode());
        }

        try {

            HttpServletResponse response = ServletActionContext.getResponse();
            String filename="区域.xls";
            if(ServletActionContext.getRequest().getHeader("User-Agent").contains("Firefox")){
                filename="=?UTF-8?B?"+ new String(new BASE64Encoder().encode(filename.getBytes("UTF-8"))) + "?=";
            }else {
                filename= URLEncoder.encode(filename,"UTF-8").replace("+"," ");
            }

            response.setContentType(ServletActionContext.getServletContext().getMimeType(filename));//完成文件下载不要忘了"一个流，两个头"
            response.setHeader("content-disposition", "attachment;filename=" + filename);
            hssfWorkbook.write(response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return SUCCESS;
    }

    @Action(value = "area_findAll", results = {@Result(name = "success", type = "json")})
    public String findAll() {
        List<Area> all = areaService.findAll();
        ActionContext.getContext().getValueStack().push(all);
        return SUCCESS;
    }

    @Action(value = "area_save",results = {@Result(name="success",type = "redirect",location = "./pages/base/area.html")})
    public String save() {
        areaService.save(model);

        return SUCCESS;
    }

    @Action(value = "area_findProvince", results = {@Result(name = "success", type = "json")})
    public String findProvince() {
        List<String> all = areaService.findProvince();
        List<Area> areas = new ArrayList<>();
        for (String str:
             all) {
            Area area = new Area();
            area.setProvince(str);
            areas.add(area);
        }
        ActionContext.getContext().getValueStack().push(areas);
        return SUCCESS;
    }
    @Action(value = "area_findCity", results = {@Result(name = "success", type = "json")})
    public String findCity() {
        String province = model.getProvince();
        try {
            province=new String(province.getBytes("ISO-8859-1"),"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        List<String> all = areaService.findCity(province);
        List<Area> areas = new ArrayList<>();
        for (String str:
            all) {
            Area area = new Area();
            area.setCity(str);
            areas.add(area);
        }
        ActionContext.getContext().getValueStack().push(areas);
        return SUCCESS;
    }
    @Action(value = "area_findDistrict", results = {@Result(name = "success", type = "json")})
    public String findDistrict() {
        String province = model.getProvince();
        String city = model.getCity();
        try {
            province=new String(province.getBytes("ISO-8859-1"),"UTF-8");
            city=new String(city.getBytes("ISO-8859-1"),"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        List<String> all = areaService.findDistrict(province,city);
        List<Area> areas = new ArrayList<>();
        for (String str:
            all) {
            Area area = new Area();
            area.setDistrict(str);
            areas.add(area);
        }
        ActionContext.getContext().getValueStack().push(areas);
        return SUCCESS;
    }
    @Action(value = "area_findArea", results = {@Result(name = "success", type = "json")})
    public String findArea() {
        List<Area> areas = areaService.findArea(model.getProvince(),model.getCity(),model.getDistrict());

        ActionContext.getContext().getValueStack().push(areas);
        return SUCCESS;
    }





}
